package cn.com.efuture.o2o.backend.mybatis.service;

import cn.com.efuture.o2o.backend.mybatis.entity.Module;
import cn.com.efuture.o2o.backend.mybatis.entity.Role;
import cn.com.efuture.o2o.backend.mybatis.mapper.RoleMapper;
import cn.com.efuture.o2o.backend.system.JsonResponse;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RoleServiceImpl {

    @Autowired
    private RoleMapper roleMapper;

    public int addRole(Map<String, Object> map) {
        return roleMapper.addRole(map);
    }

    public List<Role> getRoleList(Map<String, Object> map) {
        return roleMapper.getRoleList(map);
    }

    public int updateRole(Map<String, Object> map) {
        return roleMapper.updateRole(map);
    }

    public String getRoleModule(Map<String, Object> map) {
        List<Module> allModule = roleMapper.getModule(map);
        List<Module> roleModule = roleMapper.getRoleModule(map);
        List<Integer> list = new ArrayList<>();
        for (Module module : roleModule) {
            int moduleId = module.getModuleId();
            list.add(moduleId);
        }
        JSONObject json = new JSONObject();
        json.put("allModule", allModule);
        json.put("roleModuleId", list);
        return json.toString();
    }

    @Transactional
    public void addRoleModule(Map<String, Object> map) {
        Map<String, Object> tempMap = new HashMap<>();
        String roleId = map.get("roleId").toString();
        tempMap.put("roleId", roleId);
        roleMapper.deleteRoleModule(tempMap);
        String[] moduleList = map.get("moduleId").toString().split(",");
        for (String moduleId : moduleList) {
            Map<String, Object> module = new HashMap<>();
            module.put("roleId", roleId);
            module.put("moduleId", moduleId);
            roleMapper.addRoleModule(module);
        }
    }
    
    public String getModuleList(Map<String, Object> map) {
    	 List<Module> moduleList = roleMapper.getModule(map);
    	 JSONObject json = new JSONObject();
    	 json.put("moduleList", moduleList);
    	 json.put("status", 200);
    	 return json.toString();
    }

	public int saveModuleMessage(Map<String, Object> map) {
		return roleMapper.saveModuleMessage(map);
	}

	public int checkRoleName(Map<String, Object> map) {
		 return roleMapper.checkRoleName(map);
	}
}
